'use client';

import { useState, useEffect, createContext, useContext } from 'react';
import { Globe, ChevronDown, Check } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';

// 支持的语言列表
const SUPPORTED_LANGUAGES = {
  'zh-CN': {
    name: '简体中文',
    nativeName: '简体中文',
    flag: '🇨🇳',
    code: 'zh-CN',
  },
  en: {
    name: 'English',
    nativeName: 'English',
    flag: '🇺🇸',
    code: 'en',
  },
} as const;

type LanguageCode = keyof typeof SUPPORTED_LANGUAGES;

// 语言上下文
interface LanguageContextType {
  currentLanguage: LanguageCode;
  setLanguage: (lang: LanguageCode) => void;
  t: (key: string, params?: Record<string, string>) => string;
}

const LanguageContext = createContext<LanguageContextType | undefined>(
  undefined
);

// 翻译文本
const translations = {
  'zh-CN': {
    // 通用
    'common.loading': '加载中...',
    'common.error': '错误',
    'common.success': '成功',
    'common.cancel': '取消',
    'common.confirm': '确认',
    'common.save': '保存',
    'common.edit': '编辑',
    'common.delete': '删除',
    'common.search': '搜索',
    'common.back': '返回',
    'common.next': '下一步',
    'common.previous': '上一步',
    'common.home': '首页',
    'common.docs': '文档',
    'common.community': '社区',
    'common.contact': '联系我们',

    // 导航
    'nav.solutions': '解决方案',
    'nav.cases': '案例研究',
    'nav.docs': '文档',
    'nav.community': '社区',
    'nav.github': 'GitHub',
    'nav.quickStart': '快速开始',

    // 主页
    'home.title': 'CActor框架 - 高性能Actor模型开发框架',
    'home.subtitle':
      '新一代高性能Actor模型开发框架，专为金融、电商等高并发场景设计',
    'home.getStarted': '立即开始',
    'home.learnMore': '了解更多',
    'home.features.title': '核心特性',
    'home.features.performance': '极致性能',
    'home.features.scalability': '线性扩展',
    'home.features.reliability': '高可靠性',

    // 解决方案
    'solutions.title': '解决方案',
    'solutions.subtitle': '针对不同行业和场景的专业解决方案',
    'solutions.hft.title': '高频交易系统',
    'solutions.hft.description': '微秒级延迟的高频交易系统，支持百万级TPS',
    'solutions.payment.title': '实时支付处理',
    'solutions.payment.description': '高可用的实时支付处理解决方案',
    'solutions.risk.title': '智能风控系统',
    'solutions.risk.description': 'AI驱动的实时风险控制系统',

    // 文档
    'docs.title': '文档',
    'docs.quickStart': '快速开始',
    'docs.apiReference': 'API参考',
    'docs.examples': '示例代码',
    'docs.bestPractices': '最佳实践',

    // 错误页面
    'error.404.title': '页面未找到',
    'error.404.description': '抱歉，您访问的页面不存在或已被移动',
    'error.500.title': '服务器内部错误',
    'error.500.description': '抱歉，服务器遇到了一个意外错误',

    // 搜索
    'search.placeholder': '搜索文档、解决方案、案例...',
    'search.noResults': '未找到相关结果',
    'search.results': '找到 {count} 个结果',

    // 主题
    'theme.light': '浅色模式',
    'theme.dark': '深色模式',
    'theme.system': '跟随系统',

    // 语言
    'language.switch': '切换语言',
    'language.current': '当前语言',
  },
  en: {
    // Common
    'common.loading': 'Loading...',
    'common.error': 'Error',
    'common.success': 'Success',
    'common.cancel': 'Cancel',
    'common.confirm': 'Confirm',
    'common.save': 'Save',
    'common.edit': 'Edit',
    'common.delete': 'Delete',
    'common.search': 'Search',
    'common.back': 'Back',
    'common.next': 'Next',
    'common.previous': 'Previous',
    'common.home': 'Home',
    'common.docs': 'Docs',
    'common.community': 'Community',
    'common.contact': 'Contact Us',

    // Navigation
    'nav.solutions': 'Solutions',
    'nav.cases': 'Case Studies',
    'nav.docs': 'Documentation',
    'nav.community': 'Community',
    'nav.github': 'GitHub',
    'nav.quickStart': 'Quick Start',

    // Home
    'home.title':
      'CActor Framework - High-Performance Actor Model Development Framework',
    'home.subtitle':
      'Next-generation high-performance Actor model development framework designed for high-concurrency scenarios like finance and e-commerce',
    'home.getStarted': 'Get Started',
    'home.learnMore': 'Learn More',
    'home.features.title': 'Core Features',
    'home.features.performance': 'Ultimate Performance',
    'home.features.scalability': 'Linear Scalability',
    'home.features.reliability': 'High Reliability',

    // Solutions
    'solutions.title': 'Solutions',
    'solutions.subtitle':
      'Professional solutions for different industries and scenarios',
    'solutions.hft.title': 'High-Frequency Trading System',
    'solutions.hft.description':
      'Microsecond-latency high-frequency trading system supporting millions of TPS',
    'solutions.payment.title': 'Real-time Payment Processing',
    'solutions.payment.description':
      'High-availability real-time payment processing solution',
    'solutions.risk.title': 'Intelligent Risk Control System',
    'solutions.risk.description': 'AI-driven real-time risk control system',

    // Documentation
    'docs.title': 'Documentation',
    'docs.quickStart': 'Quick Start',
    'docs.apiReference': 'API Reference',
    'docs.examples': 'Examples',
    'docs.bestPractices': 'Best Practices',

    // Error pages
    'error.404.title': 'Page Not Found',
    'error.404.description':
      'Sorry, the page you are looking for does not exist or has been moved',
    'error.500.title': 'Internal Server Error',
    'error.500.description':
      'Sorry, the server encountered an unexpected error',

    // Search
    'search.placeholder': 'Search docs, solutions, cases...',
    'search.noResults': 'No results found',
    'search.results': 'Found {count} results',

    // Theme
    'theme.light': 'Light Mode',
    'theme.dark': 'Dark Mode',
    'theme.system': 'System',

    // Language
    'language.switch': 'Switch Language',
    'language.current': 'Current Language',
  },
};

/**
 * 语言提供者组件
 */
interface LanguageProviderProps {
  children: React.ReactNode;
  defaultLanguage?: LanguageCode;
}

export function LanguageProvider({
  children,
  defaultLanguage = 'zh-CN',
}: LanguageProviderProps) {
  const [currentLanguage, setCurrentLanguage] =
    useState<LanguageCode>(defaultLanguage);

  useEffect(() => {
    // 从localStorage读取保存的语言设置
    const savedLanguage = localStorage.getItem(
      'cactor-language'
    ) as LanguageCode;
    if (savedLanguage && SUPPORTED_LANGUAGES[savedLanguage]) {
      setCurrentLanguage(savedLanguage);
    } else {
      // 检测浏览器语言
      const browserLanguage = navigator.language;
      if (browserLanguage.startsWith('zh')) {
        setCurrentLanguage('zh-CN');
      } else {
        setCurrentLanguage('en');
      }
    }
  }, []);

  const setLanguage = (lang: LanguageCode) => {
    setCurrentLanguage(lang);
    localStorage.setItem('cactor-language', lang);

    // 更新HTML lang属性
    document.documentElement.lang = lang;
  };

  const t = (key: string, params?: Record<string, string>): string => {
    const translation =
      (translations[currentLanguage] as any)?.[key] || (translations['zh-CN'] as any)[key] || key;

    if (params) {
      return Object.entries(params).reduce(
        (text, [param, value]) => text.replace(`{${param}}`, value),
        translation
      );
    }

    return translation;
  };

  return (
    <LanguageContext.Provider value={{ currentLanguage, setLanguage, t }}>
      {children}
    </LanguageContext.Provider>
  );
}

/**
 * 使用语言Hook
 */
export function useLanguage() {
  const context = useContext(LanguageContext);
  if (!context) {
    throw new Error('useLanguage must be used within a LanguageProvider');
  }
  return context;
}

/**
 * 语言切换组件
 */
interface LanguageToggleProps {
  className?: string;
  variant?: 'default' | 'minimal' | 'dropdown' | 'flag';
  showLabel?: boolean;
}

export function LanguageToggle({
  className,
  variant = 'default',
  showLabel = true,
}: LanguageToggleProps) {
  const { currentLanguage, setLanguage, t } = useLanguage();
  const [isOpen, setIsOpen] = useState(false);

  const currentLang = SUPPORTED_LANGUAGES[currentLanguage];

  // 默认样式
  if (variant === 'default') {
    return (
      <div className={cn('relative', className)}>
        <Button
          variant="ghost"
          size="sm"
          onClick={() => setIsOpen(!isOpen)}
          className="flex items-center space-x-2"
        >
          <Globe className="w-4 h-4" />
          {showLabel && <span>{currentLang.name}</span>}
          <ChevronDown
            className={cn(
              'w-3 h-3 transition-transform',
              isOpen && 'rotate-180'
            )}
          />
        </Button>

        {isOpen && (
          <div className="absolute top-full right-0 mt-1 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg py-1 z-50 min-w-[150px]">
            {Object.entries(SUPPORTED_LANGUAGES).map(([code, lang]) => (
              <button
                key={code}
                onClick={() => {
                  setLanguage(code as LanguageCode);
                  setIsOpen(false);
                }}
                className={cn(
                  'w-full px-3 py-2 text-left hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center justify-between',
                  currentLanguage === code &&
                    'bg-blue-50 dark:bg-blue-950 text-blue-600 dark:text-blue-400'
                )}
              >
                <div className="flex items-center space-x-2">
                  <span>{lang.flag}</span>
                  <span>{lang.name}</span>
                </div>
                {currentLanguage === code && <Check className="w-4 h-4" />}
              </button>
            ))}
          </div>
        )}

        {/* 点击外部关闭 */}
        {isOpen && (
          <div
            className="fixed inset-0 z-40"
            onClick={() => setIsOpen(false)}
          />
        )}
      </div>
    );
  }

  // 最小化样式
  if (variant === 'minimal') {
    return (
      <button
        onClick={() => {
          const nextLang = currentLanguage === 'zh-CN' ? 'en' : 'zh-CN';
          setLanguage(nextLang);
        }}
        className={cn(
          'p-2 rounded-lg transition-all duration-200',
          'text-gray-600 hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-100',
          'hover:bg-gray-100 dark:hover:bg-gray-800',
          className
        )}
        title={t('language.switch')}
      >
        <Globe className="w-4 h-4" />
      </button>
    );
  }

  // 旗帜样式
  if (variant === 'flag') {
    return (
      <div className={cn('relative', className)}>
        <Button
          variant="ghost"
          size="sm"
          onClick={() => setIsOpen(!isOpen)}
          className="flex items-center space-x-2 px-2"
        >
          <span className="text-lg">{currentLang.flag}</span>
          {showLabel && (
            <span className="text-sm">{currentLang.code.toUpperCase()}</span>
          )}
        </Button>

        {isOpen && (
          <div className="absolute top-full right-0 mt-1 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg py-1 z-50">
            {Object.entries(SUPPORTED_LANGUAGES).map(([code, lang]) => (
              <button
                key={code}
                onClick={() => {
                  setLanguage(code as LanguageCode);
                  setIsOpen(false);
                }}
                className={cn(
                  'w-full px-3 py-2 text-left hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center space-x-2',
                  currentLanguage === code && 'bg-blue-50 dark:bg-blue-950'
                )}
              >
                <span className="text-lg">{lang.flag}</span>
                <span className="text-sm">{lang.nativeName}</span>
                {currentLanguage === code && (
                  <Check className="w-3 h-3 ml-auto" />
                )}
              </button>
            ))}
          </div>
        )}

        {isOpen && (
          <div
            className="fixed inset-0 z-40"
            onClick={() => setIsOpen(false)}
          />
        )}
      </div>
    );
  }

  return null;
}

/**
 * 翻译文本组件
 */
interface TranslateProps {
  k: string;
  params?: Record<string, string>;
  className?: string;
  as?: keyof JSX.IntrinsicElements;
}

export function Translate({
  k,
  params,
  className,
  as: Component = 'span',
}: TranslateProps) {
  const { t } = useLanguage();

  return <Component className={className}>{t(k, params)}</Component>;
}

/**
 * 语言检测Hook
 */
export function useLanguageDetection() {
  const { currentLanguage, setLanguage } = useLanguage();

  const detectBrowserLanguage = () => {
    const browserLanguage = navigator.language;
    if (browserLanguage.startsWith('zh')) {
      return 'zh-CN' as LanguageCode;
    }
    return 'en' as LanguageCode;
  };

  const autoSetLanguage = () => {
    const detectedLanguage = detectBrowserLanguage();
    if (detectedLanguage !== currentLanguage) {
      setLanguage(detectedLanguage);
    }
  };

  return {
    currentLanguage,
    detectBrowserLanguage,
    autoSetLanguage,
  };
}

/**
 * 语言切换动画Hook
 */
export function useLanguageTransition() {
  const { currentLanguage, setLanguage } = useLanguage();
  const [isTransitioning, setIsTransitioning] = useState(false);

  const transitionToLanguage = (newLanguage: LanguageCode, duration = 300) => {
    if (newLanguage === currentLanguage) return;

    setIsTransitioning(true);

    // 添加过渡效果
    document.body.style.transition = `opacity ${duration}ms ease-in-out`;
    document.body.style.opacity = '0.7';

    setTimeout(() => {
      setLanguage(newLanguage);

      setTimeout(() => {
        document.body.style.opacity = '1';
        setTimeout(() => {
          document.body.style.transition = '';
          setIsTransitioning(false);
        }, duration);
      }, 50);
    }, duration / 2);
  };

  return {
    currentLanguage,
    isTransitioning,
    transitionToLanguage,
  };
}
